package com.fdb.efp.nls.service.impl.dw;

import com.fdb.basic.framework.core.constant.BaseConstant;
import com.fdb.basic.framework.core.constant.CountryConstant;
import com.fdb.basic.framework.core.constant.CurrencyConstant;
import com.fdb.basic.framework.core.constant.MonAlrmLvlEnums.MonAlrmLvlEnum;
import com.fdb.basic.framework.core.constant.SDicCertTypeEnum;
import com.fdb.basic.framework.core.util.DateTool;
import com.fdb.basic.framework.core.util.StringUtil;
import com.fdb.basic.framework.core.util.ValidationUtils;
import com.fdb.efp.nls.common.constant.BdLoanConstant;
import com.fdb.efp.nls.service.domain.TxtFileLoadBean;
import com.fdb.efp.nls.service.domain.dw.BdYxapplyBean;
import com.fdb.efp.nls.service.facade.dw.BdYxApplyBatchService;
import com.fdb.efp.nls.service.util.DueDataUtil;
import com.fdb.efp.nls.service.util.SDicMappingUtil;
import com.fdb.efp.nls.service.util.TxtFileLoadPluginBatch;
import com.fdb.efp.esb.common.constant.MsLoanConstant;
import com.fdb.efp.nls.service.facade.AccoutErroTempService;
import com.fdb.efp.nls.service.facade.DwBaiduOpenTempService;
import com.fdb.efp.nls.service.vo.AccoutErroTempVO;
import com.fdb.efp.nls.service.facade.BdSxapplyTempService;
import com.fdb.efp.nls.service.facade.BdYxapplyTempService;
import com.fdb.efp.nls.service.facade.NlsApplyInfoService;
import com.fdb.efp.nls.service.vo.NlsApplyInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 根据百度同步过来的用信申请文件信息临时表数据修改用信申请基本信息表
 * 
 * @author weijj
 * @since 2019年5月7日 下午2:35:12
 * @version 1.0
 */
@Service("bdYxApplyBatchService")
public class BdYxApplyBatchServiceImpl implements BdYxApplyBatchService {

	private static Logger logger = LoggerFactory.getLogger(BdYxApplyBatchServiceImpl.class);

	@Autowired
	@Qualifier("nlsApplyInfoService")
	private NlsApplyInfoService nlsApplyInfoService;// 用信申请基本信息

	@Autowired
	@Qualifier("bdYxapplyTempService")
	private BdYxapplyTempService bdYxapplyTempService;// 用信申请临时信息

	@Autowired
	@Qualifier("bdSxapplyTempService")
	private BdSxapplyTempService bdSxapplyTempService;// 授信申请临时信息

	@Autowired
	@Qualifier("dwBaiduOpenTempService")
	private DwBaiduOpenTempService dwBaiduOpenTempService;// 贷款每日放款明细临时信息

	@Autowired
	@Qualifier("accoutErroTempService")
	private AccoutErroTempService accoutErroTempService;// 错误信息

	// /**
	// * 根据百度同步过来的用信申请文件信息临时表数据修改用信申请基本信息表 <br>
	// * 0.1: weijj:2019年5月7日 下午3:02:37:新增 <br>
	// *
	// * @author weijj
	// * @since 2019年5月7日 下午3:02:37
	// * @date 2019年5月7日 下午3:02:37
	// * @version 0.1
	// */
	// @Override
	// public boolean batchUpdateYxApply() throws Exception {
	// // TODO Auto-generated method stub
	// boolean result = false;
	// long startTime = System.currentTimeMillis();
	// logger.info("同步用信申请文件信息文件数据到用信申请基本信息表：[" + DateTool.formatDate(new
	// Date(startTime), DateTool.PATTERN_DATETIME) + "]， 处理开始");
	// // 可以配置参数
	// Integer pageSize = 1000;
	// try {
	// // 需要新增或者修改的用信申请基本信息
	// List<NlsApplyInfoVO> list = null;
	// // 分页信息
	// BdYxapplyTempVO pageInfo = new BdYxapplyTempVO();
	// // 新增或者修改的用信申请基本信息数量
	// int num = 0;
	// // 页数
	// int page = 1;
	// // pageSize初始化
	// if (pageSize > 0) {
	// pageInfo.setSize(pageSize);
	// } else {
	// pageInfo.setSize(1000);
	// }
	// final String createUser = "admin";
	// // 判断循环次数
	// int size = bdYxapplyTempService.queryCount();
	// String size_msg = "【用信申请基本信息表】数据量：" + size;
	// logger.info(size_msg, "message{}");
	// int loopCount = (size / pageInfo.getSize()) + 1;
	// // 授信申请信息
	// // BdSxapplyTempVO inBdSxapplyTempVO = new BdSxapplyTempVO();
	// // 用信事务ID
	// // String yxTransactionId = "";
	// for (int i = 0; i < loopCount; i++) {
	// // 分页查询【用信申请信息表】数据
	// List<BdYxapplyTempVO> tempList = bdYxapplyTempService.queryByPage(pageInfo);
	// list = new ArrayList<NlsApplyInfoVO>();
	// if (tempList != null && !tempList.isEmpty()) {
	// for (BdYxapplyTempVO bdYxapplyTempVO : tempList) {
	// // 用信申请基本信息
	// NlsApplyInfoVO nlsApplyInfoVO = new NlsApplyInfoVO();
	// // yxTransactionId = bdYxapplyTempVO.getTransactionid();
	// // inBdSxapplyTempVO.setTransactionid(yxTransactionId);
	// // // 根据事务ID查询授信申请信息
	// // BdSxapplyTempVO bdSxapplyTempVO =
	// // bdSxapplyTempService.queryByTransactionId(inBdSxapplyTempVO);
	// // String sessionId = "";
	// // if (bdSxapplyTempVO != null) {
	// // // 会话ID
	// // sessionId = bdSxapplyTempVO.getSessionid();
	// // } else {
	// // String tableName = "bd_sxapply_temp";
	// // String errorMsg = "未查询到授信申请信息，还款方式：" + sessionId + "，授信事务号：" +
	// // yxTransactionId;
	// // addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg,
	// // errorMsg);
	// // logger.error(errorMsg);
	// // }
	// nlsApplyInfoVO.setApplySeq(bdYxapplyTempVO.getSessionid());
	// nlsApplyInfoVO.setCusName(bdYxapplyTempVO.getName());
	// nlsApplyInfoVO.setCertType(SDicCertTypeEnum.IDCARD.getValue());
	// nlsApplyInfoVO.setCertCode(bdYxapplyTempVO.getPrcid());
	// nlsApplyInfoVO.setMobile(bdYxapplyTempVO.getPhonenumber());
	// // apply_date 申请日期
	// nlsApplyInfoVO.setApplyDate(DueDataUtil.getApplyDateValue(bdYxapplyTempVO.getTrantime(),
	// BdLoanConstant.NO_0));
	// // apply_time 申请时间
	// nlsApplyInfoVO.setApplyTime(DueDataUtil.getApplyDateValue(bdYxapplyTempVO.getTrantime(),
	// BdLoanConstant.YES_1));
	// nlsApplyInfoVO.setApplyAmt(StringUtil.isNullorBank(bdYxapplyTempVO.getCashamount())
	// ? BigDecimal.ZERO
	// : new BigDecimal(bdYxapplyTempVO.getCashamount()));
	// nlsApplyInfoVO.setNlsApplyState(
	// SDicMappingUtil.getLocalSysDicVal(BdLoanConstant.NLS_APPLY_STATE,
	// bdYxapplyTempVO.getIsblack()));
	// if (StringUtil.isNullorBank(bdYxapplyTempVO.getIsblack())) {
	// nlsApplyInfoVO.setNlsApplyState(MsLoanConstant.NlsApplyStateEnum.PASS.VALUE);
	// }
	// if (BdLoanConstant.YES_1.equals(bdYxapplyTempVO.getIsblack())) {
	// nlsApplyInfoVO.setRefuseCause("是黑名单");
	// } else {
	// nlsApplyInfoVO.setRefuseCause("");
	// }
	// nlsApplyInfoVO.setLoanPurpose(BdLoanConstant.LOAN_USE_TYPE_23);
	// // prd_id 产品ID ICODE 百度分配的机构码
	// nlsApplyInfoVO.setPrdId(SDicMappingUtil.getLocalSysDicVal(BdLoanConstant.PRD_CODE,
	// bdYxapplyTempVO.getIcode()));
	// nlsApplyInfoVO.setPrdCode(SDicMappingUtil.getLocalSysDicVal(BdLoanConstant.PRD_CODE,
	// bdYxapplyTempVO.getIcode()));
	// // prd_name 产品名称 ICODE 百度分配的机构码
	// nlsApplyInfoVO.setPrdName(SDicMappingUtil.getLocalSysDicVal(BdLoanConstant.PRD_NAME,
	// bdYxapplyTempVO.getIcode()));
	// nlsApplyInfoVO.setCreateUser(createUser);
	// nlsApplyInfoVO.setCreateTime(DueDataUtil.getApplyDateValue(bdYxapplyTempVO.getTrantime(),
	// BdLoanConstant.YES_1));
	// nlsApplyInfoVO.setLastModifyUser(createUser);
	// nlsApplyInfoVO.setLastModifyTime(DateTool.getCurrentDateTime());
	// nlsApplyInfoVO.setLoanCcy(CurrencyConstant.CNY);
	// try {
	// // indiv_sex 性别 从证件信息中获取性别
	// String indivSex =
	// ValidationUtils.getSexFromIdNumber(nlsApplyInfoVO.getCertCode()).getEnname();
	// nlsApplyInfoVO.setCusGender(indivSex);
	// } catch (Exception e) {
	// String remark = "获取客户性别信息失败，申请流水号[" + nlsApplyInfoVO.getApplySeq() +
	// "]，客户名称[" + nlsApplyInfoVO.getCusName()
	// + "]";
	// logger.error(remark);
	// }
	// nlsApplyInfoVO.setCusNational(CountryConstant.CHN);
	// nlsApplyInfoVO.setRecvAcctNo(bdYxapplyTempVO.getBankcard());
	// nlsApplyInfoVO.setAmountOfLoan(bdYxapplyTempVO.getCashamount());
	// nlsApplyInfoVO.setChannelNo(BdLoanConstant.BD_CHANNEL_NO);
	// nlsApplyInfoVO.setBdIdpicture0(bdYxapplyTempVO.getIdpicture0());
	// nlsApplyInfoVO.setBdIdpicture1(bdYxapplyTempVO.getIdpicture1());
	// nlsApplyInfoVO.setBdLivingPhoto(bdYxapplyTempVO.getLivingphoto());
	// nlsApplyInfoVO.setBdUnionLoanUsed(bdYxapplyTempVO.getUnionloanused());
	// // nlsApplyInfoVO.setLmtApplySeq(sessionId);
	// nlsApplyInfoVO.setBdIdpictureState(BdLoanConstant.YES_2);
	// nlsApplyInfoVO.setBdReqSn(bdYxapplyTempVO.getReqsn());
	// nlsApplyInfoVO.setBdTransactionId(bdYxapplyTempVO.getTransactionid());
	// nlsApplyInfoVO.setBdReasonCode(bdYxapplyTempVO.getReasoncode());
	// nlsApplyInfoVO.setBdReasonMsg(bdYxapplyTempVO.getReasonmsg());
	// nlsApplyInfoVO.setBdRisCode(bdYxapplyTempVO.getRiscode());
	// nlsApplyInfoVO.setBdOrderId(bdYxapplyTempVO.getOrderid());
	// list.add(nlsApplyInfoVO);
	// }
	// // 需要新增或者更新的用信申请基本信息
	// if (list != null && !list.isEmpty()) {
	// int updateSize = nlsApplyInfoService.insertOrUpdateNlsApplyInfo(list);
	// num += updateSize;
	// }
	// }
	// pageInfo.setPage(++page);
	// }
	// String num_msg = "【用信申请基本信息表】插入或更新数据处理结果:" + num;
	// logger.info(num_msg, "message{}");
	// result = true;
	// } catch (Exception e) {
	// e.printStackTrace();
	// String tableName = "nls_apply_info";
	// String errorMsg = "同步用信申请文件数据到用信申请基本信息表出错";
	// String remark = "同步用信申请文件数据到用信申请基本信息表出错，错误信息：" + e.getMessage();
	// addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg,
	// remark);
	// logger.error(remark);
	// throw new Exception(remark);
	// }
	// long endTime = System.currentTimeMillis();
	// logger.info("同步用信申请文件数据到用信申请基本信息表：[" + DateTool.formatDate(new Date(endTime),
	// DateTool.PATTERN_DATETIME) + "]， 处理结束");
	// logger.info("SERIOUS，耗时：[" + (endTime - startTime) / 1000.0 + "]秒，处理结果[" +
	// result + "]");
	// return result;
	// }

	/**
	 * 根据百度同步过来的用信申请文件信息数据修改用信申请基本信息表 <br>
	 * 0.1: weijj:2019年5月7日 下午3:02:37:新增 <br>
	 * 
	 * @author weijj
	 * @since 2019年5月7日 下午3:02:37
	 * @date 2019年5月7日 下午3:02:37
	 * @version 0.1
	 */
	@Override
	public boolean batchUpdateYxApply(String fileUrl) throws Exception {
		// 处理结果
		boolean result = false;
		long startTime = System.currentTimeMillis();
		logger.info("同步用信申请文件信息文件数据到用信申请基本信息表：[" + DateTool.formatDate(new Date(startTime), DateTool.PATTERN_DATETIME) + "]， 处理开始");
		try {
			TxtFileLoadPluginBatch txtFileLoadPlugin = new TxtFileLoadPluginBatch(fileUrl, "\u0002", "UTF-8", 0, 1000);
			List<TxtFileLoadBean> txtFileLoadList = txtFileLoadPlugin.run(new BdYxapplyBean());
			result = dueData(txtFileLoadList);
			if (txtFileLoadList.size() != 0) {
				while (!txtFileLoadList.get(txtFileLoadList.size() - 1).isReadedComplete) {
					txtFileLoadPlugin.setFirstRead(false);
					txtFileLoadList = txtFileLoadPlugin.run(new BdYxapplyBean());
					if (txtFileLoadList.size() == 0) {
						break;
					}
					result = dueData(txtFileLoadList);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			String tableName = "nls_apply_info";
			String errorMsg = "同步用信申请文件数据到用信申请基本信息表出错";
			String remark = "同步用信申请文件数据到用信申请基本信息表出错，错误信息：" + e.getMessage();
			addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg, remark);
			logger.error(remark);
			throw new Exception(remark);
		}
		long endTime = System.currentTimeMillis();
		logger.info("同步用信申请文件数据到用信申请基本信息表：[" + DateTool.formatDate(new Date(endTime), DateTool.PATTERN_DATETIME) + "]， 处理结束");
		logger.info("SERIOUS，耗时：[" + (endTime - startTime) / 1000.0 + "]秒，处理结果[" + result + "]");
		return result;
	}

	/**
	 * 根据百度同步过来的用信申请文件信息数据加工初始化用信申请基本信息 <br>
	 * 0.1: weijj:2019年5月7日 下午3:02:37:新增 <br>
	 * 
	 * @author weijj
	 * @since 2019年5月7日 下午3:02:37
	 * @date 2019年5月7日 下午3:02:37
	 * @version 0.1
	 */
	public boolean dueData(List<TxtFileLoadBean> txtFileLoadList) {
		logger.info("同步用信申请文件数据到用信申请基本信息表加工处理开始！");
		// 需要新增或者修改的网贷申请基本信息
		List<NlsApplyInfoVO> list = new ArrayList<NlsApplyInfoVO>();
		// 处理结果
		boolean result = false;
		// 新增或者修改的数量
		int num = 0;
		// 创建、修改用户
		final String createUser = "admin";
		BdYxapplyBean bdYxapplyBean = new BdYxapplyBean();
		try {
			for (int i = 0; i < txtFileLoadList.size(); i++) {
				bdYxapplyBean = (BdYxapplyBean) txtFileLoadList.get(i);
				// 网贷申请基本信息
				NlsApplyInfoVO nlsApplyInfoVO = new NlsApplyInfoVO();
				// yxTransactionId = bdYxapplyTempVO.getTransactionid();
				// inBdSxapplyTempVO.setTransactionid(yxTransactionId);
				// // 根据事务ID查询授信申请信息
				// BdSxapplyTempVO bdSxapplyTempVO =
				// bdSxapplyTempService.queryByTransactionId(inBdSxapplyTempVO);
				// String sessionId = "";
				// if (bdSxapplyTempVO != null) {
				// // 会话ID
				// sessionId = bdSxapplyTempVO.getSessionid();
				// } else {
				// String tableName = "bd_sxapply_temp";
				// String errorMsg = "未查询到授信申请信息，还款方式：" + sessionId + "，授信事务号：" +
				// yxTransactionId;
				// addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg,
				// errorMsg);
				// logger.error(errorMsg);
				// }
				nlsApplyInfoVO.setApplySeq(bdYxapplyBean.getSessionid());
				nlsApplyInfoVO.setCusName(bdYxapplyBean.getName());
				nlsApplyInfoVO.setCertType(SDicCertTypeEnum.IDCARD.getValue());
				nlsApplyInfoVO.setCertCode(bdYxapplyBean.getPrcid());
				nlsApplyInfoVO.setMobile(bdYxapplyBean.getPhonenumber());
				// apply_date 申请日期
				nlsApplyInfoVO.setApplyDate(DueDataUtil.getApplyDateValue(bdYxapplyBean.getTrantime(), BdLoanConstant.NO_0));
				// apply_time 申请时间
				nlsApplyInfoVO.setApplyTime(DueDataUtil.getApplyDateValue(bdYxapplyBean.getTrantime(), BdLoanConstant.YES_2));
				if(!StringUtil.isNullorBank(bdYxapplyBean.getCashamount())) {
					nlsApplyInfoVO.setApplyAmt(new BigDecimal(bdYxapplyBean.getCashamount()));
				}
				nlsApplyInfoVO
						.setNlsApplyState(SDicMappingUtil.getLocalSysDicVal(BdLoanConstant.NLS_APPLY_STATE, bdYxapplyBean.getIsblack()));
				if (StringUtil.isNullorBank(bdYxapplyBean.getIsblack())) {
					nlsApplyInfoVO.setNlsApplyState(MsLoanConstant.NlsApplyStateEnum.PASS.VALUE);
				}
				if(MsLoanConstant.NlsApplyStateEnum.PASS.VALUE.equals(nlsApplyInfoVO.getNlsApplyState())) {
					nlsApplyInfoVO.setDnSts(BaseConstant.DN_STS_1);
				}
				if (BdLoanConstant.YES_1.equals(bdYxapplyBean.getIsblack())) {
					nlsApplyInfoVO.setRefuseCause("是黑名单");
				} else {
					nlsApplyInfoVO.setRefuseCause("");
				}
				nlsApplyInfoVO.setLoanPurpose(BdLoanConstant.LOAN_USE_TYPE_23);
				// prd_id 产品ID ICODE 百度分配的机构码
				nlsApplyInfoVO.setPrdId(SDicMappingUtil.getLocalSysDicVal(BdLoanConstant.PRD_CODE, bdYxapplyBean.getIcode()));
				nlsApplyInfoVO.setPrdCode(SDicMappingUtil.getLocalSysDicVal(BdLoanConstant.PRD_CODE, bdYxapplyBean.getIcode()));
				// prd_name 产品名称 ICODE 百度分配的机构码
				nlsApplyInfoVO.setPrdName(SDicMappingUtil.getLocalSysDicVal(BdLoanConstant.PRD_NAME, bdYxapplyBean.getIcode()));
				nlsApplyInfoVO.setCreateUser(createUser);
				nlsApplyInfoVO.setCreateTime(DueDataUtil.getApplyDateValue(bdYxapplyBean.getTrantime(), BdLoanConstant.YES_1));
				nlsApplyInfoVO.setLastModifyUser(createUser);
				nlsApplyInfoVO.setLastModifyTime(DateTool.getCurrentDateTime());
				nlsApplyInfoVO.setLoanCcy(CurrencyConstant.CNY);
				try {
					// indiv_sex 性别 从证件信息中获取性别
					String indivSex = ValidationUtils.getSexFromIdNumber(nlsApplyInfoVO.getCertCode()).getEnname();
					nlsApplyInfoVO.setCusGender(indivSex);
				} catch (Exception e) {
					String remark = "获取客户性别信息失败，申请流水号[" + nlsApplyInfoVO.getApplySeq() + "]，客户名称[" + nlsApplyInfoVO.getCusName() + "]";
					logger.error(remark);
				}
				nlsApplyInfoVO.setCusNational(CountryConstant.CHN);
				nlsApplyInfoVO.setRecvAcctNo(bdYxapplyBean.getBankcard());
				nlsApplyInfoVO.setAmountOfLoan(bdYxapplyBean.getCashamount());
				nlsApplyInfoVO.setChannelNo(BdLoanConstant.BD_CHANNEL_NO);
				nlsApplyInfoVO.setBdIdpicture0(bdYxapplyBean.getIdpicture0());
				nlsApplyInfoVO.setBdIdpicture1(bdYxapplyBean.getIdpicture1());
				nlsApplyInfoVO.setBdLivingPhoto(bdYxapplyBean.getLivingphoto());
				nlsApplyInfoVO.setBdUnionLoanUsed(bdYxapplyBean.getUnionloanused());
				// nlsApplyInfoVO.setLmtApplySeq(sessionId);
				nlsApplyInfoVO.setBdIdpictureState(BdLoanConstant.YES_2);
				nlsApplyInfoVO.setBdReqSn(bdYxapplyBean.getReqsn());
				nlsApplyInfoVO.setBdTransactionId(bdYxapplyBean.getTransactionid());
				nlsApplyInfoVO.setBdReasonCode(bdYxapplyBean.getReasoncode());
				nlsApplyInfoVO.setBdReasonMsg(bdYxapplyBean.getReasonmsg());
				nlsApplyInfoVO.setBdRisCode(bdYxapplyBean.getRiscode());
				nlsApplyInfoVO.setBdOrderId(bdYxapplyBean.getOrderid());
				list.add(nlsApplyInfoVO);
			}
			if (list != null && !list.isEmpty()) {
				num = nlsApplyInfoService.insertOrUpdateNlsApplyInfo(list);
			}
			String num_msg = "【网贷申请基本信息表】插入或更新数据处理结果:" + num;
			logger.info(num_msg, "message{}");
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			String tableName = "nls_apply_info";
			String errorMsg = "同步用信申请文件数据到网贷申请基本信息表出错";
			String remark = "同步用信申请文件数据到网贷申请基本信息表出错，错误信息：" + e.getMessage();
			addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg, remark);
			logger.error(remark);
		} finally {
			// 清空信息
			list = null;
			txtFileLoadList = null;
		}
		logger.info("同步用信申请文件数据到用信申请基本信息表加工处理结束！");
		return result;
	}

	/**
	 * 
	 * 记录异常信息 <br>
	 * 0.1:weijj:2019年5月7日 上午11:31:23:新增 <br>
	 * 
	 * @author weijj
	 * @since 2019年5月7日 上午11:31:23
	 * @date 2019年5月7日 上午11:31:23
	 * @version 0.1
	 */
	private void addErrorInfo(String tableName, String errorType, String errorMsg, String remark) {
		AccoutErroTempVO accoutErroTempVO = new AccoutErroTempVO();
		// 表名
		accoutErroTempVO.setTableName(tableName);
		// 错误级别
		accoutErroTempVO.setErroType(errorType);
		// 错误信息
		accoutErroTempVO.setErroMsg(errorMsg);
		// 备注
		accoutErroTempVO.setRemark(remark);
		// 创建时间
		accoutErroTempVO.setCreateData(DateTool.getCurrentDateTime());
		// 修改时间
		accoutErroTempVO.setLastModifyTime(DateTool.getCurrentDateTime());
		// 记录异常信息
		accoutErroTempService.insert(accoutErroTempVO);
	}
}
